package com.example.sicnuaccountingapp.utils

import com.example.sicnuaccountingapp.data.entity.Transaction
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.temporal.ChronoUnit
import com.example.sicnuaccountingapp.data.entity.TransactionType

object StatisticsUtils {
    fun calculateDailyExpense(transactions: List<Transaction>): Map<LocalDateTime, Double> {
        return transactions
            .filter { it.type == TransactionType.EXPENSE }
            .groupBy {
                LocalDateTime.ofInstant(
                    java.time.Instant.ofEpochMilli(it.date),
                    ZoneId.systemDefault()
                ).truncatedTo(ChronoUnit.DAYS)
            }
            .mapValues { (_, transactions) ->
                transactions.sumOf { it.amount }
            }
    }

    fun calculateCategoryPercentage(transactions: List<Transaction>): Map<Long?, Double> {
        val totalAmount = transactions.sumOf { it.amount }
        return transactions
            .groupBy { it.categoryId }
            .mapValues { (_, transactions) ->
                transactions.sumOf { it.amount } / totalAmount * 100
            }
    }

    fun calculateMonthlyTrend(transactions: List<Transaction>): Map<LocalDateTime, Pair<Double, Double>> {
        return transactions
            .groupBy {
                LocalDateTime.ofInstant(
                    java.time.Instant.ofEpochMilli(it.date),
                    ZoneId.systemDefault()
                ).withDayOfMonth(1)
            }
            .mapValues { (_, transactions) ->
                val income = transactions
                    .filter { it.type == TransactionType.INCOME }
                    .sumOf { it.amount }
                val expense = transactions
                    .filter { it.type == TransactionType.EXPENSE }
                    .sumOf { it.amount }
                income to expense
            }
    }

    fun calculateWeekdayStats(transactions: List<Transaction>): Map<Int, Double> {
        return transactions
            .filter { it.type == TransactionType.EXPENSE }
            .groupBy {
                LocalDateTime.ofInstant(
                    java.time.Instant.ofEpochMilli(it.date),
                    ZoneId.systemDefault()
                ).dayOfWeek.value
            }
            .mapValues { (_, transactions) ->
                transactions.sumOf { it.amount }
            }
    }
} 